<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="roles">
              <el-table-column label="序号" type="index" width="120" :index="indexMethod" />
              <el-table-column label="角色名称" prop="name" width="240" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="small" type="success" @click="hAssign(scope.row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
              <!-- </el-table-column> -->
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                background
                :total="total"
                :page-size="pagesize"
                :current-page="page"
                :page-sizes="[1, 2, 3, 4]"
                layout="sizes,prev,pager,next"
                @current-change="hCurrentChange"
                @size-change="hSizeChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!-- 分配权限 -->
    <el-dialog
      :title=" isEith ? '编辑' : '添加' "
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogAssign"
    >
      <assignPermission ref="permissionForm" :role-id="roleId" @success="hSuccess" />
    </el-dialog>
    <!-- 新增弹框 -->
    <el-dialog
      ref="permission"
      :title=" isEith ? '编辑' : '添加' "
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
      @close="hClose"
    >

      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small">取消</el-button>
          <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- </el-dialog> -->
  </div>
</template>

<script>
import { getRolesList, delRole, addRole, editRole } from '@/api/getRoles'
import assignPermission from '@/views/settings/assignPermission.vue'

export default ({
  components: {
    assignPermission
  },
  data() {
    return {
      roleId: '', //
      showDialogAssign: false, // 分配 权限
      isEith: false, // 编辑
      showDialog: false, // 弹框
      page: 1, // 当前页数
      pagesize: 1, // 一页显示多少个
      total: 0, // 总页数
      roles: [], // 存值
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '描述不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {

    hSuccess() {
      this.showDialogAssign = false
    },
    // 点击 分配按钮
    hAssign(id) {
      // 1. 显示 弹窗
      this.showDialogAssign = true
      // 2. 保存
      this.roleId = id
      // 3. 找到子 组件， 调用它的方法发请求获取当前角色信息
      this.$nextTick(() => {
        this.$refs.permissionForm.loadPermissionById()
      })
    },
    // 清空内容
    hClose() {
      // this.roleForm = {
      //   name: '',
      //   description: ''
      // }
      this.$refs.roleForm.resetFields()
    },
    // 编辑角色
    async doEdit() {
      try {
        // 1.获取数据
        const res = await editRole(this.roleForm)
        console.log(res)
        // 3.提示信息
        this.$message.success('恭喜编辑成功')
        // 4.重新发送请求
        this.loadRoles()
        // 5. 关闭弹框
        this.showDialog = false
      } catch (error) {
        this.$message.error('添加失败')
      }
    },
    // 编辑
    hEdit(data) {
      this.isEith = true
      // 弹框
      this.showDialog = true
      // 数据回填
      this.roleForm = { ...data }
    },

    // 添加角色
    async doAdd() {
      try {
        // this.isEith = false
        // 1.获取数据
        const res = await addRole(this.roleForm)
        console.log(res)
        // 2.更新数据 并且进入到最后一页，查看刚刚添加的数据
        this.total++
        this.page = Math.ceil(this.total / this.pagesize)
        this.loadRoles()
        // 3.提示信息
        this.$message.success('恭喜添加成功')
        // 4. 关闭弹框
        this.showDialog = false
      } catch (error) {
        this.$message.error('添加失败')
      }
    },

    // 添加
    hAdd() {
      // 直接发ajax
      // addRole({ name: '小花' + Date.now(), description: '秘书' })
      // 点击 跳出弹框
      this.showDialog = true
      this.isEith = false
    },
    hSubmit() {
      // 兜底 校验
      this.$refs.roleForm.validate(valid => {
        if (valid) {
          // this.doAdd()
          this.isEith ? this.doEdit() : this.doAdd()
        }
      })
    },
    // 删除
    async doDel(id) {
      try {
        await delRole(id)
        this.$message.success('删除成功')
        if (this.roles.length === 1 && this.page > 1) {
          this.page--
        }
        // 重新渲染
        this.loadRoles()
      } catch {
        this.$message.error('删除失败')
      }
    },
    // 删除
    hDel(id) {
      console.log(id)
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.doDel(id)
      }).catch((err) => {
        console.log(err)
      })
    },
    // 控制一页多少条数据
    hSizeChange(curPageSize) {
      console.log(curPageSize)
      this.pagesize = curPageSize
      // 每次更新 都会 跳转到第一页
      this.page = 1
      // 重新加载
      this.loadRoles()
    },
    // 控制点击的页码
    hCurrentChange(curPage) {
      // 更新数据
      this.page = curPage
      // 重新加载
      this.loadRoles()
    },
    // 获取
    async loadRoles() {
      try {
        const res = await getRolesList({ page: this.page, pagesize: this.pagesize })
        this.total = res.data.total
        this.roles = res.data.rows
        console.log('res', res)
      } catch (err) {
        console.log(err)
      }
    },
    indexMethod(index) {
      // console.log(index)
      // 点击下一页 序号连续
      return (this.page - 1) * this.pagesize + index + 1
    }
  }
})
</script>
